package com.hospital.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 *
 * @author Hospital Management System
 */
@Slf4j
@Component
public class JwtUtil {

    @Value("${jwt.secret:hospital-management-system-jwt-secret-key}")
    private String secret;

    @Value("${jwt.expiration:7200}")
    private int expire;

    @Value("${jwt.header:Authorization}")
    private String header;

    /**
     * 获取签名密钥
     *
     * @return SecretKey
     */
    private SecretKey getSigningKey() {
        byte[] keyBytes = secret.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 生成JWT token
     *
     * @param userId   用户ID
     * @param username 用户名
     * @param role     用户角色
     * @return JWT token
     */
    public String generateToken(Long userId, String username, Integer role) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .claim("userId", userId)
                .claim("username", username)
                .claim("role", role)
                .signWith(getSigningKey())
                .compact();
    }

    /**
     * 解析JWT token
     *
     * @param token JWT token
     * @return Claims
     */
    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * 验证token是否过期
     *
     * @param expiration 过期时间
     * @return true：过期，false：未过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    /**
     * 验证token
     *
     * @param token JWT token
     * @return true：有效，false：无效
     */
    public boolean validateToken(String token) {
        try {
            Claims claims = getClaimByToken(token);
            return claims != null && !isTokenExpired(claims.getExpiration());
        } catch (Exception e) {
            log.error("Token validation error: ", e);
            return false;
        }
    }

    /**
     * 从token中获取用户ID
     *
     * @param token JWT token
     * @return 用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = getClaimByToken(token);
        if (claims != null) {
            return Long.valueOf(claims.get("userId").toString());
        }
        return null;
    }

    /**
     * 从token中获取用户名
     *
     * @param token JWT token
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = getClaimByToken(token);
        if (claims != null) {
            return claims.get("username").toString();
        }
        return null;
    }

    /**
     * 从token中获取用户角色
     *
     * @param token JWT token
     * @return 用户角色
     */
    public Integer getRoleFromToken(String token) {
        Claims claims = getClaimByToken(token);
        if (claims != null) {
            return Integer.valueOf(claims.get("role").toString());
        }
        return null;
    }

    /**
     * 获取token的过期时间
     *
     * @param token JWT token
     * @return 过期时间
     */
    public Date getExpirationFromToken(String token) {
        Claims claims = getClaimByToken(token);
        return claims != null ? claims.getExpiration() : null;
    }

    /**
     * 刷新token
     *
     * @param token 原token
     * @return 新token
     */
    public String refreshToken(String token) {
        Claims claims = getClaimByToken(token);
        if (claims != null) {
            Long userId = Long.valueOf(claims.get("userId").toString());
            String username = claims.get("username").toString();
            Integer role = Integer.valueOf(claims.get("role").toString());
            return generateToken(userId, username, role);
        }
        return null;
    }

    /**
     * 从请求头中获取token
     *
     * @param authHeader Authorization头信息
     * @return token
     */
    public String getTokenFromHeader(String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }

    public String getHeader() {
        return header;
    }
}